package com.example.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

@Service
@Slf4j
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSenderImpl mailSender;//注入邮件工具类

    @Async
    @Override
    public MailDto sendMail(MailDto MailDto) {
        try {
            checkMail(MailDto); //1.检测邮件
            sendMimeMail(MailDto); //2.发送邮件
            return saveMail(MailDto); //3.保存邮件
        } catch (Exception e) {
            MailDto.setStatus("fail");
            MailDto.setError(e.getMessage());
            return MailDto;
        }
    }

    @Override
    public boolean sendMail(Exception e) {
        // StringWriter将包含堆栈信息
        StringWriter stringWriter = new StringWriter();
        //必须将StringWriter封装成PrintWriter对象，
        //以满足printStackTrace的要求
        PrintWriter printWriter = new PrintWriter(stringWriter);
        //获取堆栈信息
        e.printStackTrace(printWriter);
        //转换成String，并返回该String
        StringBuffer error = stringWriter.getBuffer();
        String htmlStr = "<div>\n" +
                "<pre>" + error.toString() + "</pre>\n" +
                "</div>";
        //发送邮件
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), false);//true表示支持复杂类型
            messageHelper.setFrom(getMailSendFrom());//邮件发信人从配置项读取
            messageHelper.setTo(getMailSendTo());//邮件收信人
            messageHelper.setSubject("异常信息");//邮件主题
            messageHelper.setText(htmlStr,true);//邮件内容
            mailSender.send(messageHelper.getMimeMessage());//正式发送邮件
        }catch (Exception exception){
            log.error("send mail exception",exception);
        }
        return false;
    }

    //检测邮件信息类
    private void checkMail(MailDto MailDto) {
        if (StringUtils.isEmpty(MailDto.getTo())) {
            throw new RuntimeException("邮件收信人不能为空");
        }
        if (StringUtils.isEmpty(MailDto.getSubject())) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(MailDto.getText())) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    //构建复杂邮件信息类
    private boolean sendMimeMail(MailDto MailDto) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);//true表示支持复杂类型
            MailDto.setFrom(getMailSendFrom());//邮件发信人从配置项读取
            messageHelper.setFrom(MailDto.getFrom());//邮件发信人
            messageHelper.setTo(MailDto.getTo().split(","));//邮件收信人
            messageHelper.setSubject(MailDto.getSubject());//邮件主题
            messageHelper.setText(MailDto.getText());//邮件内容
            if (!StringUtils.isEmpty(MailDto.getCc())) {//抄送
                messageHelper.setCc(MailDto.getCc().split(","));
            }
            if (!StringUtils.isEmpty(MailDto.getBcc())) {//密送
                messageHelper.setCc(MailDto.getBcc().split(","));
            }
            if (MailDto.getMultipartFiles() != null) {//添加邮件附件
                for (MultipartFile multipartFile : MailDto.getMultipartFiles()) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }
            if (StringUtils.isEmpty(MailDto.getSentDate())) {//发送时间
                MailDto.setSentDate(new Date());
                messageHelper.setSentDate(MailDto.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage());//正式发送邮件
            MailDto.setStatus("ok");
            return true;
        } catch (Exception e) {
            log.error("send email fail",e);
        }
        return false;
    }

    //保存邮件
    private MailDto saveMail(MailDto MailDto) {
        //将邮件保存到数据库..
        return MailDto;
    }

    //获取邮件发信人
    public String getMailSendFrom() {
        return mailSender.getJavaMailProperties().getProperty("from");
    }

    //获取邮件发信人
    public String getMailSendTo() {
        return mailSender.getJavaMailProperties().getProperty("to");
    }
}